#!/usr/bin/env node

/**
 * 🔄 品牌自动更新脚本
 * 
 * 根据 brand.config.ts 中的配置，自动更新所有相关文件
 * 
 * 使用方法：
 *   node scripts/update-brand.js
 */

import { readFileSync, writeFileSync, readdirSync, statSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const ROOT_DIR = join(__dirname, '..')

// 读取品牌配置
console.log('📖 读取品牌配置...')
const brandConfigPath = join(ROOT_DIR, 'brand.config.ts')
const brandConfigContent = readFileSync(brandConfigPath, 'utf-8')

// 提取配置信息（简单的正则匹配）
const extractConfig = (key) => {
  const match = brandConfigContent.match(new RegExp(`${key}:\\s*['"]([^'"]+)['"]`))
  return match ? match[1] : null
}

const BRAND = {
  nameCN: extractConfig('nameCN'),
  nameEN: extractConfig('nameEN'),
  packageScope: extractConfig('packageScope'),
  teamName: extractConfig('teamName'),
  platformName: extractConfig('platformName'),
  systemTitle: extractConfig('systemTitle'),
}

console.log('✅ 品牌配置读取成功:')
console.log(JSON.stringify(BRAND, null, 2))

/**
 * 递归查找所有 package.json 文件
 */
function findPackageJsonFiles(dir, files = []) {
  const items = readdirSync(dir)
  
  for (const item of items) {
    const fullPath = join(dir, item)
    const stat = statSync(fullPath)
    
    if (stat.isDirectory()) {
      // 跳过 node_modules 和 dist 目录
      if (item !== 'node_modules' && item !== 'dist' && item !== '.git') {
        findPackageJsonFiles(fullPath, files)
      }
    } else if (item === 'package.json') {
      files.push(fullPath)
    }
  }
  
  return files
}

/**
 * 更新 package.json 文件
 */
function updatePackageJson(filePath) {
  try {
    const content = readFileSync(filePath, 'utf-8')
    const pkg = JSON.parse(content)
    let modified = false
    
    // 更新包名
    if (pkg.name && pkg.name.startsWith('@')) {
      const oldScope = pkg.name.split('/')[0].substring(1)
      const packageName = pkg.name.split('/')[1]
      const newName = `@${BRAND.packageScope}/${packageName}`
      
      if (pkg.name !== newName) {
        console.log(`  📦 ${pkg.name} → ${newName}`)
        pkg.name = newName
        modified = true
      }
    }
    
    // 更新 author
    if (pkg.author && pkg.author.includes('Team')) {
      pkg.author = BRAND.teamName
      modified = true
    }
    
    // 更新依赖中的包名
    const depTypes = ['dependencies', 'devDependencies', 'peerDependencies']
    for (const depType of depTypes) {
      if (pkg[depType]) {
        const deps = pkg[depType]
        const newDeps = {}
        
        for (const [key, value] of Object.entries(deps)) {
          if (key.startsWith('@') && key.includes('/')) {
            const [oldScope, packageName] = key.split('/')
            const newKey = `@${BRAND.packageScope}/${packageName}`
            newDeps[newKey] = value
            
            if (key !== newKey) {
              modified = true
            }
          } else {
            newDeps[key] = value
          }
        }
        
        if (modified) {
          pkg[depType] = newDeps
        }
      }
    }
    
    // 保存修改
    if (modified) {
      writeFileSync(filePath, JSON.stringify(pkg, null, 2) + '\n', 'utf-8')
      return true
    }
    
    return false
  } catch (error) {
    console.error(`❌ 更新失败: ${filePath}`, error.message)
    return false
  }
}

/**
 * 更新 TypeScript/Vue 文件中的导入语句
 */
function updateImports(dir) {
  const files = []
  
  function findFiles(directory) {
    const items = readdirSync(directory)
    
    for (const item of items) {
      const fullPath = join(directory, item)
      const stat = statSync(fullPath)
      
      if (stat.isDirectory()) {
        if (item !== 'node_modules' && item !== 'dist' && item !== '.git') {
          findFiles(fullPath)
        }
      } else if (item.endsWith('.ts') || item.endsWith('.vue') || item.endsWith('.js')) {
        files.push(fullPath)
      }
    }
  }
  
  findFiles(dir)
  
  let count = 0
  for (const file of files) {
    try {
      let content = readFileSync(file, 'utf-8')
      const originalContent = content
      
      // 替换导入语句中的包名
      content = content.replace(/@\w+\/([\w-]+)/g, (match, packageName) => {
        return `@${BRAND.packageScope}/${packageName}`
      })
      
      if (content !== originalContent) {
        writeFileSync(file, content, 'utf-8')
        count++
      }
    } catch (error) {
      // 忽略错误
    }
  }
  
  return count
}

// 主流程
console.log('\n🚀 开始更新品牌信息...\n')

// 1. 更新所有 package.json
console.log('📦 更新 package.json 文件...')
  const packagesDir = join(ROOT_DIR, 'tuxing-packages')
const packageJsonFiles = findPackageJsonFiles(packagesDir)
let updatedCount = 0

for (const file of packageJsonFiles) {
  const relativePath = file.replace(ROOT_DIR, '')
  process.stdout.write(`  处理: ${relativePath}`)
  
  if (updatePackageJson(file)) {
    console.log(' ✅')
    updatedCount++
  } else {
    console.log(' ⏭️')
  }
}

console.log(`\n✅ 更新了 ${updatedCount} 个 package.json 文件\n`)

// 2. 更新导入语句
console.log('📝 更新导入语句...')
const importCount = updateImports(packagesDir)
console.log(`✅ 更新了 ${importCount} 个文件的导入语句\n`)

console.log('🎉 品牌更新完成！\n')
console.log('💡 建议执行以下命令：')
console.log('   cd packages')
console.log('   pnpm install')
console.log('   pnpm -r build\n')

